#include "regutil.h"
#include "util.h"

bool have_key(HKEY root_key, const TCHAR * sub_key)
{
	HKEY Key;
	RegOpenKeyEx(root_key, sub_key, 0, KEY_READ, &Key);
	if (Key == 0)
		return false;
	RegCloseKey(Key);
	return true;
}
DWORD reg_get_dword(HKEY root_key, 
					const TCHAR * sub_key, 
					const TCHAR * value_name, 
					DWORD def_value)
{
	HKEY TestKey = 0;
	DWORD type;
	DWORD DataLength = 16; 
	char Data[16];
	RegOpenKeyEx(root_key, sub_key, 0, KEY_READ, &TestKey);
	if (TestKey == 0)
		return def_value;
	LONG Res = RegQueryValueEx(TestKey, value_name, 0, &type, (LPBYTE)Data, &DataLength);
	if (Res != ERROR_SUCCESS || type != REG_DWORD)
	{
		RegCloseKey(TestKey);
		return def_value;
	}
	DWORD *v = (DWORD*)Data;
	RegCloseKey(TestKey);
	return *v;
}

std::wstring reg_get_string(HKEY root_key, 
							const TCHAR * sub_key, 
							const TCHAR * value_name)
{
	const unsigned int string_length = 1024;
	HKEY TestKey = 0;
	DWORD type;
	DWORD DataLength = string_length;
	RegOpenKeyEx(root_key, sub_key, 0, KEY_READ, &TestKey);
	if (TestKey == 0)
		return std::wstring();
	TCHAR *ReadString = new TCHAR[string_length];
	LONG Res = RegQueryValueEx(TestKey, value_name, 0, &type, (LPBYTE)ReadString, &DataLength);
	if (Res != ERROR_SUCCESS || type != REG_SZ)
	{
		RegCloseKey(TestKey);
		return std::wstring();
	}
	RegCloseKey(TestKey);
#ifdef UNICODE
	return std::wstring(ReadString);
#else
	WCHAR *WString = new WCHAR[string_length];
	MultiCharToWideChar(std::string(ReadString));
	return std::wstring(WString);
#endif
}
